package com.share.thread;

public class ProducerConsumer {
	public static void main(String[] args) {
		SyncStack ss = new SyncStack();
		Producer p = new Producer(ss);
		Consumer c = new Consumer(ss);
		new Thread(p).start();
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();
	}
}

class WoTou { // 窝窝头
	int id; // 窝窝头id

	WoTou(int id) {
		this.id = id;
	}

	public String toString() {
		return "WoTou : " + id;
	}
}

class SyncStack {// 同步栈
	int index = 0;// 下标
	WoTou[] arrWT = new WoTou[6];// 窝窝头的数组..假设只能装6个窝窝头

	public synchronized void push(WoTou wt) {// 装窝窝头的筐子..放窝窝头
		while (index == arrWT.length) {
			try {
				this.wait(); // 如果筐子满了，就休息会。。。（等待）当前正在访问的线程wait-----this
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll(); // ....当前正在访问的线程唤醒notifyAll-----this
		arrWT[index] = wt;
		index++;
	}

	public synchronized WoTou pop() {// 拿窝窝头
		while (index == 0) {
			try {
				this.wait(); // 如果拿完了筐子里的窝窝头。
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll(); // 唤醒
		index--;
		return arrWT[index];
	}
}

class Producer implements Runnable {// 生产者，生产窝窝头............厨师
	SyncStack ss = null;

	Producer(SyncStack ss) {
		this.ss = ss;
	}

	public void run() {
		for (int i = 0; i < 20; i++) {
			WoTou wt = new WoTou(i);
			ss.push(wt);
			System.out.println("生产了：" + wt);
			try {
				Thread.sleep((int) (Math.random() * 200));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Consumer implements Runnable {// 消费者..........消费窝窝头..........吃的人
	SyncStack ss = null;

	Consumer(SyncStack ss) {
		this.ss = ss;
	}

	public void run() {
		for (int i = 0; i < 20; i++) {
			WoTou wt = ss.pop();
			System.out.println("消费了: " + wt);
			try {
				Thread.sleep((int) (Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
